package me.zhengjie.common.utils.byteUtils

/**
 *
 * Author:Think
 *
 * Time:2021/2/3 16:58
 *
 * Description:This is IEEE754
 *
 */
object IEEE754 {
    /**
     *
     * @Desc: IEEE754标准(四字节转浮点数),公式转换
     *
     * @Author: Aries.hu
     *
     * @Date: 2021/2/3 10:14
     */
    fun hex2FloatIeee(hex: ByteArray): Float {
        val hexStr = DataTransform.bytesToHex(hex)
        val binaryStr = StringBuilder()
        run {
            var i = 0
            while (i < hexStr!!.length) {
                val a = hexStr.substring(i, i + 2)
                val c = a.toInt(16)
                val item = String.format("%08d", Integer.toBinaryString(c).toInt())
                binaryStr.append(item)
                i += 2
            }
        }
        val n = binaryStr.substring(1, 9).toInt(2)
        val mStr = binaryStr.substring(9, binaryStr.length - 1)
        var sum = 0.0
        for (i in 1..mStr.length) {
            if (mStr[i - 1] == '1') {
                sum = sum + Math.pow(0.5, i.toDouble())
            }
        }
        return (Math.pow(2.0, (n - 127).toDouble()) * (1 + sum)).toFloat()
    }

    /**
     *
     * @Desc: IEEE754标准(四字节转浮点数)调用JDK接口转换
     *
     * @Author: Aries.hu
     *
     * @Date: 2021/2/5 10:23
     */
    fun hex2floatIeeeApi(bytes: ByteArray?, reverse: Boolean): Float {
        var bytes = bytes
        if (reverse) {
            bytes = DataTransform.bytesArrayReverse(bytes)
        }
        val hex = DataTransform.encodeHexStr(bytes, true)
        return java.lang.Float.intBitsToFloat(Integer.valueOf(hex, 16))
    }

    /**
     *
     * @Desc: IEEE754标准(浮点数转四字节)调用JDK接口转换
     *
     * @Author: Aries.hu
     *
     * @Date: 2021/2/5 11:57
     */
    fun float2hexIeeeApi(f: Float): ByteArray? {
        val intBits = java.lang.Float.floatToRawIntBits(f)
        return DataTransform.intToByteArray(intBits)
    }
}